package site;


import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.SystemException;

@Stateful
public class ConnexionManager {
		
	@PersistenceContext
	EntityManager em;
	
	public boolean verifier(String n) {
		 @SuppressWarnings("unchecked")
		ArrayList<String> a = (ArrayList<String>)em.createNamedQuery("verif").getResultList();
		 boolean test = true ;
		 int i = 0 ;
		 while(test && i<a.size()) {
			 test = !(a.get(i).equals(n));
			 i++;
		 }
		 return test ;
	}
	

	public void ajouterArticle(String titre, int jj, int mm,
			int aaaa, String contenu) {
		
			@SuppressWarnings("deprecation")
			Date dateArticle = new Date (aaaa-1900,mm,jj);
			Article article = new Article ();
			article.setTitre(titre);
			article.setContenu(contenu);
			article.setDateArticle(dateArticle);
			em.persist(article);
	}

	
	public void register(String n , String p, String l, String e, String m) {
		Utilisateur u = new Utilisateur() ;
		u.setNom(n);
		u.setPrenom(p);
		u.setLogin(l);
		u.setEmail(e);
		u.setPassword(m);
		em.persist(u);
	}
	
	public String getNom(String l){
		return  (String) em.createNamedQuery("Nom").setParameter("login", l).getSingleResult() ;
	}
	
	public String getPrenom(String l){
		return  (String) em.createNamedQuery("Prenom").setParameter("login", l).getSingleResult() ;
	}
	
	@SuppressWarnings("unchecked")
	public ArrayList<Integer> getIdLogin(String l) {
		return ((ArrayList<Integer>) em.createNamedQuery("idLogin").setParameter("login", l).getResultList()) ;
	}
	
	@SuppressWarnings("unchecked")
	public ArrayList<Integer> getIdPW(String l) {
		return ((ArrayList<Integer>) em.createNamedQuery("idPW").setParameter("password", l).getResultList()) ;
	}

	public EcoleIng addEcole(String e) {
		@SuppressWarnings("unchecked")
		ArrayList<EcoleIng> ei = (ArrayList<EcoleIng>) em.createNamedQuery("ecole").setParameter("ecole", e).getResultList() ;
		if (ei.isEmpty()) {
			EcoleIng eing = new EcoleIng() ;
			eing.setNomEcole(e);
			em.persist(eing);
			return eing ;
		}
		else {
			return ei.get(0);
		}
	}

	public void addMembre(int i, String n, String p, String e) throws IllegalStateException, SecurityException, SystemException {
			Membre m = new Membre() ;
			EcoleIng ei = this.addEcole(e);
			
			m.setDateAdhesion(Calendar.getInstance());
			m.setId(i);
			m.setEcole(ei);
			em.merge(ei);
			m.setNationalite(n);
			m.setVilleActuelle(p);
			em.merge(m);
			//em.persist(m);	
	}

}
